import { _decorator, Component, Layers, Node, resources, Sprite, SpriteFrame, UITransform } from 'cc';
const { ccclass, property } = _decorator;
import Levels from '../../Levels';
import { createUINode, randomByRange } from '../../Utils';
import { TileManager } from './TileManager';
import DataManager from '../../Runtime/DataManager';
import ResourceManager from '../../Runtime/ResourceManager';

@ccclass('TileMapManager')
export class TileMapManager extends Component {
    async init() {
        const { mapInfo } = DataManager.Instance;

        const spriteFrames = await ResourceManager.Instance.loadDir('texture/tile/tile', SpriteFrame);
        DataManager.Instance.tileInfo = [];
        for (let i = 0; i < mapInfo.length; i += 1) {
            const column = mapInfo[i];
            DataManager.Instance.tileInfo[i] = [];
            for (let j = 0; j < column.length; j += 1) {
                const item = column[j];

                if (item.src === null || item.type === null) {
                    continue;
                }

                const node = createUINode();

                const tileManager = node.addComponent(TileManager);

                let imgNum = item.src;
                if (j % 2 === 0 && i % 2 === 0) {
                    if (imgNum === 1 || imgNum === 5 || imgNum === 9) {
                        imgNum += randomByRange(0, 4);
                    }
                }
                const imgSrc = `tile (${imgNum})`;

                const spriteFrame = spriteFrames.find(v => v.name === imgSrc) || spriteFrames[0];
                tileManager.init(item.type, spriteFrame, i, j);
                DataManager.Instance.tileInfo[i][j] = tileManager;
                node.setParent(this.node);
            }
        }
    }
}

